<template>
  <div class="secondhand-container">
    <!-- 搜索和发布区域 -->
    <el-card class="search-card">
      <div class="search-header">
        <el-input v-model="searchQuery" placeholder="搜索二手商品..." class="search-input" clearable>
          <template #prefix>
            <el-icon>
              <search />
            </el-icon>
          </template>
        </el-input>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button type="success" @click="showAddDialog = true">发布商品</el-button>
      </div>

      <!-- 分类标签 -->
      <div class="category-tags">
        <el-tag v-for="tag in categories" :key="tag.value" :type="selectedCategory === tag.value ? '' : 'info'"
                class="category-tag" @click="selectCategory(tag.value)">
          {{ tag.label }}
        </el-tag>
      </div>
    </el-card>

    <!-- 商品列表 -->
    <div class="items-grid">
      <el-empty v-if="items.length === 0" description="暂无商品" />
      <el-card v-for="item in items" :key="item.id" class="item-card">
        <div class="item-image">
          <el-image :src="`${item.imageUrl}`" fit="cover" />
          <div class="item-price">¥{{ item.price }}</div>
        </div>
        <div class="item-info">
          <h4 class="item-title">{{ item.title }}</h4>
          <p class="item-description">{{ item.description }}</p>
          <div class="item-footer">
            <div class="seller-info">
              <el-avatar :src="item.user.avatarUrl" :size="24" />
              <span>{{ item.user.username }}</span>
            </div>
            <el-button type="primary" size="small" @click="contactSeller(item)">
              联系卖家
            </el-button>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 添加商品的弹窗 -->
    <el-dialog title="发布商品" v-model="showAddDialog" width="500">
      <el-form :model="newItem" :rules="rules" ref="addFormRef">
        <el-form-item label="标题" prop="title">
          <el-input v-model="newItem.title" placeholder="请输入商品标题" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="newItem.description" type="textarea" placeholder="请输入商品描述" />
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input v-model="newItem.price" placeholder="请输入价格" />
        </el-form-item>
        <el-form-item label="图片" prop="image" style="margin-left: 10px;">
          <el-upload action="http://localhost:6005/api/files/upload" method="post" :show-file-list="false"
                     :on-success="handleUploadSuccess" :on-error="handleUploadError" :before-upload="beforeUpload">
            <!-- 条件渲染：显示图片或加号图标 -->
            <div style="width: 100px; height: 100px; cursor: pointer; display: flex; align-items: center;
               justify-content: center; background-color: #f5f5f5; border: 1px dashed #ccc;">
              <el-image v-if="newItem.imageUrl" :src="newItem.imageUrl" style="width: 100%; height: 100%;"
                        fit="cover" />
              <el-icon v-else>
                <plus />
              </el-icon>
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showAddDialog = false">取消</el-button>
          <el-button type="primary" @click="publishItem">确认发布</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Search, Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { bookApi } from '../api/book'
import { authApi } from '../api/auth'
import { profileApi } from '../api/profile'

const searchQuery = ref('')
const selectedCategory = ref('')
const showAddDialog = ref(false)

const categories = [
  { label: '全部', value: '' },
  { label: '教材书籍', value: 'books' },
  { label: '电子产品', value: 'electronics' },
  { label: '生活用品', value: 'daily' },
  { label: '运动器材', value: 'sports' },
  { label: '其他', value: 'other' }
]
const items = ref([])

const addFormRef = ref(null)
const newItem = reactive({
  title: '',
  description: '',
  price: '',
  imageUrl: ''
})

const rules = {
  title: [{ required: true, message: '请输入商品标题', trigger: 'blur' }],
  description: [{ required: true, message: '请输入商品描述', trigger: 'blur' }],
  price: [{ required: true, message: '请输入价格', trigger: 'blur' }]
}

const selectedBook = reactive({
  title: '',
  description: '',
  price: '',
  user: { username: '' }
})

// 获取当前用户 ID
const userId = ref(null)
const token = ref(localStorage.getItem('token') || '')
const fetchUserId = async () => {
  try {
    const response = await authApi.getUserInfo(token)
    userId.value = response.data.id
  } catch (error) {
    ElMessage.error('获取个人资料失败')
  }
}

const publishItem = async () => {
  // TODO: 实现发布商品功能
  if (!addFormRef.value) return
  try {
    await addFormRef.value.validate()
    const bookData = { ...newItem, user: { id: userId.value } }
    const response = await bookApi.addBook(bookData)
    ElMessage.success(response.data.message || '教材添加成功')
    Object.keys(newItem).forEach((key) => (newItem[key] = ''))
    showAddDialog.value = false
    fetchBooks()
  } catch (error) {
    console.log(error)
    ElMessage.error(error.response?.data?.message || '添加教材失败')
  }
}
//搜索教材
const handleSearch = async () => {
  try {
    const response = await bookApi.searchBooks(searchQuery.value)
    items.value = response.data.books
    ElMessage.success(response.data.message || '搜索成功')
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '搜索失败')
  }
}

const contactSeller = (item) => {
  // TODO: 实现联系卖家功能
}

const handleUploadSuccess = (response) => {
  newItem.imageUrl = response; // 保存图片 URL
  ElMessage.success('图片上传成功');
};

const handleUploadError = () => {
  ElMessage.error('图片上传失败');
};

// 获取用户头像
const fetchUserAvatar = async (userId) => {
  try {
    const response = await profileApi.getProfile(userId); // 调用后端接口获取用户 profile
    return response.data.avatarUrl
  } catch (error) {
    console.error(`获取用户头像失败 (userId: ${userId})`, error);
    return 'https://via.placeholder.com/40'; // 返回默认头像
  }
};


// 获取教材列表
const fetchBooks = async () => {
  try {
    const response = await bookApi.getAllBooks()
    const books = response.data.books
    items.value = response.data.books

    // 为每本书加载用户头像
    const booksWithAvatars = await Promise.all(
        books.map(async (book) => {
          const avatarUrl = await fetchUserAvatar(book.user.id); // 根据 userId 获取头像
          return { ...book, user: { ...book.user, avatarUrl } }; // 将 avatarUrl 添加到 user 对象中
        })
    );

    items.value = booksWithAvatars;
  } catch (error) {
    console.log(error)
    ElMessage.error('获取教材列表失败')
  }
}
// 初始化加载教材列表
onMounted(() => {
  if (!token.value) {
    ElMessage.error('请先登录')
    return
  }
  fetchUserId().then(() => {
    fetchBooks()
  })
})
</script>

<style scoped>
.secondhand-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.search-header {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}

.search-input {
  flex: 1;
}

.category-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.category-tag {
  cursor: pointer;
}

.items-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 20px;
  margin-top: 20px;
}

.item-card {
  transition: all 0.3s;
}

.item-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.item-image {
  position: relative;
  height: 200px;
  overflow: hidden;
}

.item-image .el-image {
  width: 100%;
  height: 100%;
}

.item-price {
  position: absolute;
  bottom: 0;
  left: 0;
  background-color: rgba(0, 0, 0, 0.6);
  color: white;
  padding: 4px 8px;
  font-size: 16px;
  font-weight: bold;
}

.item-info {
  padding: 12px;
}

.item-title {
  margin: 0 0 8px 0;
  font-size: 16px;
  color: #333;
}

.item-description {
  margin: 0 0 12px 0;
  font-size: 14px;
  color: #666;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.item-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.seller-info {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #999;
  font-size: 14px;
}
</style>